<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <template #header>
          <department-item :department="company" @add="addDepart" />
        </template>
        <!-- 下拉树的数据就是 departs-->
        <el-tree :data="departs">
          <!-- 默认插槽 域名插槽 传递的是对象结构后得到data  包含departs的数据-->
          <template #default="{data}">
            <!-- 组件通信  department事件 传递的数据data-->
            <department-item allow-modify :department="data" @reload="loadDepartments" @add="addDepart" @edit="editDepart" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <department-dialog ref="addDepartment" @reload="loadDepartments" />
  </div>
</template>

<script>
// 导入组件
import DepartmentItem from './component/department-item.vue'

// 导入请求department方法
import { getDepartments, getSingleDepartment } from '@/api/departments'
// 导入方法
import { searchSubDepart } from '@/utils'
import DepartmentDialog from './component/department-dialog.vue'
export default {
  components: {
    DepartmentItem,
    DepartmentDialog
  },
  data() {
    return {
      departs: [],
      company: {},
      // defaultProps: {
      //   children: 'children',
      //   label: 'name'
      // },
      loading: true
    }
  },
  // 数据渲染结束的时候就发起请求
  created() {
    this.loadDepartments()
  },
  // 封装成方法
  methods: {
    async loadDepartments() {
      try {
        const res = await getDepartments()
        // console.log(res)
        const { depts, companyName } = res
        this.company = { name: companyName, id: '' }
        this.departs = searchSubDepart(depts, '')
        // console.log(this.departs)
      } catch (error) {
        console.log(error)
      } finally {
        // 不过结果如何加载中都要结束
        this.loading = false
      }
    },
    addDepart(id) {
      this.$refs.addDepartment.show(id)
    },
    async editDepart(id) {
      const res = await getSingleDepartment(id)
      this.$refs.addDepartment.show(res)
    }
  }
}
</script>

<style></style>
